package interfaces.hud.pilot.equipment;

import logic.items.ItemType;
import logic.ships.equipmentListener.EquipmentListener;
import logic.ships.equipmentListener.ItemChangedEvent;
import logic.ships.equipmentListener.WeaponChangedEvent;
import logic.ships.hunter.Hunter;

import org.fenggui.binding.render.Binding;
import org.fenggui.binding.render.ITexture;
import org.fenggui.binding.render.Pixmap;
import org.fenggui.decorator.background.PixmapBackground;
import org.fenggui.event.ButtonPressedEvent;
import org.fenggui.event.IButtonPressedListener;

import interfaces.GUISource;
import interfaces.hud.BasicHUD;
import interfaces.superWidgets.InterfaceButton;
import interfaces.superWidgets.InterfaceLabel;
import interfaces.superWidgets.StaticContent;

public class ItemButton extends StaticContent {
	
	private InterfaceButton button;
	private InterfaceLabel label;
	private Hunter hunter;
	private ItemType itemType;
	private BasicHUD hud;
	
	public ItemButton(int width, int height, int x, int y, String imagePath, Hunter hunter, 
			ItemType itemType, BasicHUD hud) {
		super(width, height, x, y);
		this.hunter = hunter;
		this.itemType = itemType;
		this.hud = hud;
		
		init(imagePath);
	}
	
	private void init(String imagePath) {
		try {
			button = new InterfaceButton(GUISource.smallestFont);
			button.setSize(width / 2, height);
			
			ITexture normalTexture = Binding.getInstance().getTexture(imagePath);
			Pixmap normal = new Pixmap(normalTexture);
			button.getAppearance().add(new PixmapBackground(normal, true));
			
			button.addButtonPressedListener(new IButtonPressedListener() {
				@Override
				public void buttonPressed(ButtonPressedEvent e) {
					if(hunter.getItemsAmount(itemType) > 0) 
						hunter.useItem(itemType);
				}
			});
			addWidget(button);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		label = new InterfaceLabel("0", GUISource.smallFont);
		label.setSize(width / 2, height);
		label.setXY(button.getWidth(), 0);
		addWidget(label);
		
		hud.addListener(hunter, new EquipmentListener() {
			@Override
			public void itemUsed(ItemChangedEvent event) {
				updateLabel();
			}
			
			@Override
			public void itemRemoved(ItemChangedEvent event) {
				updateLabel();
			}
			
			@Override
			public void itemAdded(ItemChangedEvent event) {
				updateLabel();
			}
			
			@Override
			public void weaponAdded(WeaponChangedEvent event) {}
			@Override
			public void weaponRemoved(WeaponChangedEvent event) {}
		});
		
		updateLabel();
	}
	
	private void updateLabel() {
		label.setText(hunter.getItemsAmount(itemType) + "");
	}
}